package com.art8173.controller;

import com.art8173.pojo.PageResult;
import com.art8173.pojo.Result;
import com.art8173.pojo.Student;
import com.art8173.pojo.StudentQueryParam;
import com.art8173.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

@RequestMapping("/students")
@Slf4j
@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 分页查询
     */
    @GetMapping
    public Result page(StudentQueryParam studentQueryParam) {
        log.info("分页查询，参数：{}", studentQueryParam);
        PageResult pageResult = studentService.page(studentQueryParam);
        return Result.success(pageResult);
    }

    /**
     * 新增学生
     */
    @PostMapping
    public Result save(@RequestBody Student student) {
        log.info("新增学生，参数：{}", student);
        studentService.save(student);
        return Result.success();
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据ID查询，id：{}", id);
        Student student = studentService.getInfo(id);
        return Result.success(student);
    }

    /**
     * 修改学生
     */
    @PutMapping
    public Result update(@RequestBody Student student) {
        log.info("修改学生，参数：{}", student);
        studentService.update(student);
        return Result.success();
    }

    /**
     * 批量删除学生
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids) {
        log.info("批量删除学生: ids={} ", ids);

        // 将逗号分隔的字符串转换为Integer列表
        ArrayList<Integer> idList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toCollection(ArrayList::new));
//        ArrayList<Integer> idList = new ArrayList<Integer>();
//        String[] idArray = ids.split(",");
//        for (String id : idArray) {
//            idList.add(Integer.valueOf(id));
//        }

        studentService.deleteByIds(idList);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result updateViolation(@PathVariable Integer id, @PathVariable Short score){
        log.info("修改学生违规分数，id: {}, score: {}", id, score);
        studentService.updateViolation(id, score);
        return Result.success();
    }
}
